﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Graphics.Printing;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinApp.View.UserControl;
using com.IronOne.BoardPACWinAppBO.Agenda;
using com.IronOne.BoardPACWinAppBO.General;
using com.IronOne.BoardPACWinAppBO.Meeting;
using com.IronOne.BoardPACWinAppBO.Paper;
using com.IronOne.BoardPACWinAppBO.Sync;
using com.IronOne.BoardPACWinAppService.Agenda;
using com.IronOne.BoardPACWinAppService.Auth;
using com.IronOne.BoardPACWinAppService.Sync;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;
using CompleteReader.Data;
using CompleteReader.Settings;
using GalaSoft.MvvmLight.Messaging;
using pdftron.PDF;
using pdftron.PDF.Tools;
using pdftron.PDF.Tools.Controls;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace com.IronOne.BoardPACWinApp.View.Page
{
    /// <summary>
    ///     A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class NewsAndShardDocsPage
    {
        public NewsAndShardDocsPage()
        {
            try
            {
                InitializeComponent();
                NavigationHelper = new NavigationHelper(this);

                _asm = new AppSettingsManager();
                _navigationService = new NavigationService();
                _dialogService = new DialogService();
                _agendaService = new AgendaService();
                _syncService = new SyncService();
                _authService = new AuthService();

                if (_asm.GetAppBarPinnedStatus())
                    PinnedAppBarButton.IsChecked = true;

                #region PDFTron

                _pdfViewCtrl = new PDFViewCtrl();
                PdfViewCtrlBorder.Child = _pdfViewCtrl;

                _pdfViewCtrl.SetZoomLimits(ZoomLimitMode.e_zoom_limit_relative, 0.1, 20); // Double size 3 times.
                _pdfViewCtrl.SetBackgroundColor(Color.FromArgb(255, 255, 255, 255));

                _pdfViewCtrl.SetProgressiveRendering(true);
                _pdfViewCtrl.SetPageRefViewMode(PDFViewCtrlPageViewMode.e_fit_width);
                _pdfViewCtrl.SetPageViewMode(_pdfViewCtrl.GetPageRefViewMode());

                _pdfViewCtrl.SetupThumbnails(false, true, true, 0, 100 * 1024 * 1024, 0.1);
                _pdfViewCtrl.SetPagePresentationMode(PDFViewCtrlPagePresentationMode.e_single_continuous);

                Loaded += ViewerPage_Loaded;
                _toolManager = new ToolManager(_pdfViewCtrl)
                {
                    EnablePopupMenuOnLongPress = false,
                    UseSmallPageNumberIndicator = false
                };
                PageNumberBorder.Child = _toolManager.PageNumberIndicator;

                OutlineDialog.PDFViewCtrl = _pdfViewCtrl;
                QuickSettings.PDFViewCtrl = _pdfViewCtrl;
                FindTextDialog.PDFViewCtrl = _pdfViewCtrl;

                _pdfViewCtrl.OnPageNumberChanged += PDFViewCtrl_OnPageNumberChanged;

                SetPagePresentationMode();
                SetNightMode();

                #endregion
            }
            catch (Exception)
            {
            }
        }

        public NavigationHelper NavigationHelper { get; private set; }

        protected override async void HandleMessages(NotificationMessage<MessageDataModel> mdm)
        {
            try
            {
                base.HandleMessages(mdm);
                await BasePage.GetInstance().HandleMessages(mdm);

                if (!mdm.Notification.Equals(MessageCodes.SYNC_UPDATED_DATA)) return;

                //If Past paper
                if (GlobalSelectdItem != null && GlobalSelectdItem.DocType != (int)PaperTypes.NewsItem &&
                    GlobalSelectdItem.DocType != (int)PaperTypes.SharedDoc)
                    return;

                var sudm = (SyncUpdatedDataModel)mdm.Content.MessageData;

                if ((sudm.AgendaItemIds == null || sudm.AgendaItemIds.Count <= 0) &&
                    (!sudm.IsUpdatedOrDeletedAgendaItems)) return;

                //News and shared doc Items
                var newsAndSharedDocs = await _agendaService.GetNewsAndSharedDocsList();

                if (GlobalSelectdItem != null && (GlobalSelectdItem.DocType == (int)PaperTypes.NewsItem &&
                                                  (newsAndSharedDocs.NewsItems != null &&
                                                   newsAndSharedDocs.NewsItems.Count > 0)))
                {
                    await
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                            () =>
                            {
                                NewsSharedDocsListView.ItemsSource = newsAndSharedDocs.NewsItems;
                                int index;
                                try
                                {
                                    index =
                                        newsAndSharedDocs.NewsItems.FindIndex(
                                            x => x.PaperId == GlobalSelectdItem.PaperId);
                                }
                                catch (Exception)
                                {
                                    index = 0;
                                }
                                NewsSharedDocsListView.SelectedIndex = index;
                            });
                }

                if (GlobalSelectdItem != null && (GlobalSelectdItem.DocType == (int)PaperTypes.SharedDoc &&
                                                  (newsAndSharedDocs.SharedDocs != null &&
                                                   newsAndSharedDocs.SharedDocs.Count > 0)))
                {
                    await
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                            () =>
                            {
                                NewsSharedDocsListView.ItemsSource = newsAndSharedDocs.SharedDocs;
                                int index;
                                try
                                {
                                    index =
                                        newsAndSharedDocs.SharedDocs.FindIndex(
                                            x => x.PaperId == GlobalSelectdItem.PaperId);
                                }
                                catch (Exception)
                                {
                                    index = 0;
                                }
                                NewsSharedDocsListView.SelectedIndex = index;
                            });
                }
            }
            catch (Exception)
            {
            }
        }

        private NewsAndSharedDocModel _model;
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                NavigationHelper.OnNavigatedTo(e);

                #region PDFTron

                QuickSettings.PresentationModeChanged += QuickSettings_PresentationModeChanged;
                QuickSettings.NightModeChanged += QuickSettings_NightModeChanged;
                QuickSettings.RotateClockwiseRequested += QuickSettings_RotateClockwiseRequested;
                QuickSettings.ThumbnailViewRequested += QuickSettings_ThumbnailViewRequested;
                _pdfViewCtrl.KeyDown += PDFViewCtrl_KeyDown;
                _pdfViewCtrl.IsEnabledChanged += PDFViewCtrl_IsEnabledChanged;

                // printing
                _pdfPrintManager = PDFPrintManager.GetInstance();

                var loader = ResourceLoader.GetForCurrentView("Printing");
                //new Windows.ApplicationModel.Resources.ResourceLoader();
                _pdfPrintManager.SetResourceLoader(loader);

                // standard options
                _pdfPrintManager.AddStandardPrintOption(StandardPrintTaskOptions.MediaSize);
                _pdfPrintManager.AddStandardPrintOption(StandardPrintTaskOptions.Orientation);

                // PDFTron options
                _pdfPrintManager.AddUserOptionAnnotations();
                _pdfPrintManager.AddUserOptionAutoRotate();
                _pdfPrintManager.AddUserOptionPageRange();

                #endregion

                _panelWidth = (int)(Window.Current.Bounds.Width * PanelPropotion);
                if (_panelWidth < Utility.GetFlyoutDefaultWidth()) _panelWidth = Utility.GetFlyoutDefaultWidth();
                _model = new NewsAndSharedDocModel
                {
                    ItemsListFlyoutWidth = _panelWidth
                };

                var items = e.Parameter as List<PaperModel>;

                if (items != null && items[0].DocType == (int)PaperTypes.NewsItem)
                {
                    //News
                    _model.PageHeading = "news";
                    _model.PageSubHeading = "view news";
                    _model.SidebarHeading = "News";
                }
                if (items != null && items[0].DocType == (int)PaperTypes.SharedDoc)
                {
                    //Shared Documents
                    _model.PageHeading = "shared documents";
                    _model.PageSubHeading = "view shared documents";
                    _model.SidebarHeading = "Shared documents";
                }

                //NOTE: NewsSharedDocsListView_SelectionChanged executes before ViewerPage_Loaded
                //because of that appbars will be null forever. So ViewerPage_Loaded's code brought here.
                _thumbSliderAppBar = BottomAppBar;
                _topAppBar = TopAppBar;

                if (items != null &&
                    (items[0].DocType == (int)PaperTypes.NewsItem || items[0].DocType == (int)PaperTypes.SharedDoc))
                {
                    _model.ListVisitibility = Visibility.Visible;
                    _model.GridVisibility = Visibility.Collapsed;
                    _model.NewsSharedDocsList = items;
                    DataContext = _model;

                    int index;
                    try
                    {
                        index = _model.NewsSharedDocsList.FindIndex(x => x.PaperId == GlobalSelectdItem.PaperId);
                    }
                    catch (Exception)
                    {
                        index = 0;
                    }

                    GlobalSelectdItem = null;
                    NewsSharedDocsListView.SelectedIndex = index == -1 ? 0 : index;
                    return;
                }

                if (items != null && items[0].DocType != (int)PaperTypes.NewsItem &&
                    items[0].DocType != (int)PaperTypes.SharedDoc) //Past paper
                {
                    _model.PageHeading = "past papers view";
                    _model.PageSubHeading = items[0].DocName.ToLower();
                    _model.SidebarHeading = "Paper info";

                    AppBarButtonOutline.Visibility = Visibility.Visible;

                    _model.ListVisitibility = Visibility.Collapsed;
                    _model.GridVisibility = Visibility.Visible;
                    _model.PpDocTypeIconPath = items[0].PpDocTypeIconPath;
                    _model.PpMeetingDateDisplay = items[0].PpMeetingDateDisplay;
                    _model.PpMeetingSubCategory = items[0].PpMeetingSubCategory;
                    _model.PpPaperStatusValue = items[0].PpPaperStatusValue;
                    _model.PpPaperRefNo = items[0].PaperRefNo;

                    DataContext = _model;

                    GlobalSelectdItem = items[0];

                    DetachAppBars();
                    await LoadPaperCommon(true);
                    AttachAppBars();
                }
            }
            catch (Exception)
            {
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedFrom(e);
                NavigationHelper.OnNavigatedFrom(e);

                #region PDFTron

                /*await CloseDoc();
                this.ToolManager.Dispose();
                PDFDoc doc = PDFViewCtrl.GetDoc();
                PDFViewCtrl.CloseDoc();
                PDFViewCtrl.FreeResources();
                PDFViewCtrl.Dispose();

                _PDFPrintManager.UnRegisterForPrintingContract();
                if (doc != null)
                {
                    doc.Dispose();
                }*/

                QuickSettings.PresentationModeChanged -= QuickSettings_PresentationModeChanged;
                QuickSettings.NightModeChanged -= QuickSettings_NightModeChanged;
                QuickSettings.RotateClockwiseRequested -= QuickSettings_RotateClockwiseRequested;
                QuickSettings.ThumbnailViewRequested -= QuickSettings_ThumbnailViewRequested;
                _pdfViewCtrl.KeyDown -= PDFViewCtrl_KeyDown;
                _pdfViewCtrl.IsEnabledChanged -= PDFViewCtrl_IsEnabledChanged;

                if (_thumbSliderAppBar != null)
                {
                    _thumbSliderAppBar.Content = null;
                }

                _pdfPrintManager.UnRegisterForPrintingContract();

                #endregion
            }
            catch (Exception)
            {
            }
        }

        private void ViewerPage_Loaded(object sender, RoutedEventArgs e)
        {
            //NOTE: NewsSharedDocsListView_SelectionChanged executes before ViewerPage_Loaded
            //because of that appbars will be null forever. So ViewerPage_Loaded's code brought to OnNavigatedTo()

            //_ThumbSliderAppBar = this.BottomAppBar;
            //_TopAppBar = this.TopAppBar as CommandBar;
        }

        private bool _isOpen = true;
        //private double _panelPropotionSize = 0;
        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _pdfViewCtrl.VerticalAlignment = VerticalAlignment.Top;

            var ss = e.NewSize.Width * PanelPropotion;
            if (e.NewSize.Width <= Utility.GetNarrowWidthSize())
            {
                if (_isOpen)
                {
                    _model.ItemsListFlyoutWidth = Utility.GetNarrowWidthSize() - 30;
                    return;
                }
                _pdfViewCtrl.Width = (e.NewSize.Width - (PdfViewerBorder));
            }
            else
            {
                if (ss < Utility.GetFlyoutDefaultWidth()) ss = Utility.GetFlyoutDefaultWidth();
                if (_isOpen)
                    _model.ItemsListFlyoutWidth = ss;
            }

            if (_isOpen)
                _pdfViewCtrl.Width = (e.NewSize.Width - (_model.ItemsListFlyoutWidth + PdfViewerBorder));
            else
                _pdfViewCtrl.Width = (e.NewSize.Width - (PdfViewerBorder));

            SetPagePresentationMode();
        }

        private void pageRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            _asm = null;
            _navigationService = null;
            _dialogService = null;
            _agendaService = null;
            _syncService = null;
            _authService = null;
        }

        #region Variables

        private INavigationService _navigationService;
        private IDialogService _dialogService;
        private IAgendaService _agendaService;
        private ISyncService _syncService;
        private IAuthService _authService;
        private AppSettingsManager _asm;

        public string PaperStatus { get; set; } //Approval status given by BM Or BS for the paper
        public static PaperModel GlobalSelectdItem;
        private const double AnimeTime = 0.3; //Seconds
        public bool IsCollapsed;
        private int _passwordAttempts = Utility.GetNoOfPasswordAttempts();
        private const int PdfViewerBorder = 70;
        private const double PanelPropotion = 0.25;
        private static TaskCompletionSource<bool> _oTaskCompletionSource;

        #endregion

        #region PDFTron

        private readonly PDFViewCtrl _pdfViewCtrl;
        private PDFDoc _pdfDoc;
        private NavigationParameter _param;
        private readonly ToolManager _toolManager;

        private PDFPrintManager _pdfPrintManager;
        private AppBar _thumbSliderAppBar;
        private AppBar _topAppBar;
        private ThumbnailViewer _thumbnailViewer;

        #endregion

        #region PDFTron

        private void PDFViewCtrl_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (((bool)e.NewValue))
            {
                AttachAppBars();
                FindTextDialog.IsEnabled = true;
            }
            else
            {
                FindTextDialog.IsEnabled = false;
                DetachAppBars();
            }
        }

        /*private async Task CloseDoc()
        {
            try
            {
                var doc = _pdfViewCtrl.GetDoc();
                _pdfViewCtrl.CloseDoc();

                if (doc != null)
                {
                    await CloseDocAsync(doc);
                }

                _pdfViewCtrl.FreeResources();
                //this.PDFViewCtrl.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
        }*/

        /*private IAsyncAction CloseDocAsync(PDFDoc doc)
        {
            var t = new Task(() => { doc.Dispose(); });
            t.Start();
            return t.AsAsyncAction();
        }*/

        /// <summary>
        ///     2015-07-06
        ///     Bhathiya Dasanayake
        ///     This method will only render the current page annotation. When page number changed this method will call.
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="numPages"></param>
        private void PDFViewCtrl_OnPageNumberChanged(int currentPage, int numPages)
        {
            _pdfViewCtrl.Update();
        }

        private void PDFViewCtrl_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            var state = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control);

            if ((state & CoreVirtualKeyStates.Down) != CoreVirtualKeyStates.Down) return;

            switch (e.Key)
            {
                case VirtualKey.F:
                    FindTextDialog.OpenDialog();
                    break;
            }
        }

        private IAsyncOperation<PDFDoc> GetPdfDocAsync(IBuffer file)
        {
            try
            {
                var t = new Task<PDFDoc>(() => GetPdfDoc(file));
                t.Start();
                return t.AsAsyncOperation();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private PDFDoc GetPdfDoc(IBuffer file)
        {
            return new PDFDoc(file);
        }

        private void HandlePassword()
        {
            PasswordGrid.Visibility = Visibility.Visible;
            PasswordDialog.Visibility = Visibility.Visible;
            PasswordDialog.SetFocus();
            PasswordDialog.Reset();
        }

        private void PasswordDialog_PasswordEntered(string password)
        {
            try
            {
                if (password == null)
                {
                    PasswordDialog.Visibility = Visibility.Collapsed;
                    if (_oTaskCompletionSource != null &&
                        _oTaskCompletionSource.Task.Status != TaskStatus.RanToCompletion)
                    {
                        _oTaskCompletionSource.SetResult(false);
                    }
                }
                else
                {
                    if (_pdfDoc.InitStdSecurityHandler(password))
                    {
                        _pdfDoc.InitStdSecurityHandler(password);
                        CommonPaperLoading();
                        PasswordDialog.Visibility = Visibility.Collapsed;
                        _oTaskCompletionSource.SetResult(true);
                    }
                    else
                    {
                        PasswordDialog.NotifyIncorrectPassword();
                        _passwordAttempts--;
                        if (_passwordAttempts == 0)
                            PasswordDialog_PasswordEntered(null);
                        else
                            PasswordDialog.SetFocus();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region PDFTron Flyout Management

        private void FlyoutDialogEnabled()
        {
            TapOverlayGrid.Visibility = Visibility.Visible;
        }

        private void FlyoutDialogDisabled()
        {
            TapOverlayGrid.Visibility = Visibility.Collapsed;
            OutlineDialog.CloseDialog();
        }

        private void TapOverlayGrid_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            FlyoutDialogDisabled();
        }

        #endregion FlyoutManagement

        #region PDFTron Settings

        private void QuickSettings_PresentationModeChanged()
        {
            SetPagePresentationMode();
        }

        private void SetPagePresentationMode()
        {
            CloseAppBars();
            //var oldPresentationMode = _pdfViewCtrl.GetPagePresentationMode();
            //var oldViewMode = _pdfViewCtrl.GetPageViewMode();
            _pdfViewCtrl.SetPagePresentationMode(Settings.PagePresentationMode);
        }

        private void QuickSettings_NightModeChanged()
        {
            CloseAppBars();
            SetNightMode();
        }

        private void SetNightMode()
        {
            if (Settings.NightMode)
            {
                _pdfViewCtrl.SetColorPostProcessMode(PDFRasterizerColorPostProcessMode.e_postprocess_invert);
                _pdfViewCtrl.Update(true);
            }
            else
            {
                _pdfViewCtrl.SetColorPostProcessMode(PDFRasterizerColorPostProcessMode.e_postprocess_none);
                _pdfViewCtrl.Update(true);
            }
        }

        private void QuickSettings_RotateClockwiseRequested()
        {
            _pdfViewCtrl.RotateClockwise();
        }

        private void QuickSettings_ThumbnailViewRequested()
        {
            CloseAppBars();
            ThumbnailViewGrid.Visibility = Visibility.Visible;
            _pdfViewCtrl.IsEnabled = false;
            _thumbnailViewer = new ThumbnailViewer(_pdfViewCtrl);
            if (Settings.NightMode)
            {
                ThumbnailViewGrid.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
                _thumbnailViewer.BlankPageDefaultColor = Colors.Black;
            }
            else
            {
                ThumbnailViewGrid.Background = new SolidColorBrush(Colors.Black);
            }
            _thumbnailViewer.ControlClosed += ThumbnailsViewer_ControlClosed;
            ThumbnailViewGrid.Children.Add(_thumbnailViewer);
        }

        private void ThumbnailsViewer_ControlClosed()
        {
            CloseThumbnailsViewer();
        }

        private void CloseThumbnailsViewer()
        {
            ThumbnailViewGrid.Children.Clear();
            ThumbnailViewGrid.Visibility = Visibility.Collapsed;
            _pdfViewCtrl.IsEnabled = true;
            if (_thumbnailViewer != null)
            {
                _thumbnailViewer.ControlClosed -= ThumbnailsViewer_ControlClosed;
            }
        }

        #endregion Settings

        #region Display Ui

        private void DisplayVideoPlayBackView()
        {
            BoardPaperGrid.Visibility = Visibility.Collapsed;
            VideoItemsGrid.Visibility = Visibility.Visible;

            AppBarButtonSearch.Visibility = Visibility.Collapsed;
            AppBarButtonViewMode.Visibility = Visibility.Collapsed;
            AppBarButtonViewPage.Visibility = Visibility.Collapsed;
            AppBarButtonOutline.Visibility = Visibility.Collapsed;
            ThumbnailSliderBdr.Visibility = Visibility.Collapsed;
        }

        private void DisplayPaperFullScreenView()
        {
            BoardPaperGrid.Visibility = Visibility.Visible;
            VideoItemsGrid.Visibility = Visibility.Collapsed;

            AppBarButtonSearch.Visibility = Visibility.Visible;
            AppBarButtonViewMode.Visibility = Visibility.Visible;
            AppBarButtonViewPage.Visibility = Visibility.Visible;
            AppBarButtonOutline.Visibility = Visibility.Visible;
            ThumbnailSliderBdr.Visibility = Visibility.Visible;

            MediaElementForAgenda.Pause();
        }

        private async void NewsSharedDocsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (NewsSharedDocsListView.SelectedIndex == -1) return;
                var selectedItem = (PaperModel)NewsSharedDocsListView.SelectedItem;
                if (selectedItem != null &&
                    (GlobalSelectdItem != null && GlobalSelectdItem.PaperId == selectedItem.PaperId)) return;

                GlobalSelectdItem = (PaperModel)NewsSharedDocsListView.SelectedItem;

                DetachAppBars();
                await LoadPaperCommon(false);
            }
            catch (Exception)
            {
            }
            finally
            {
                AttachAppBars();
            }
        }

        private void MiddleSlider_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsCollapsed) //Open
                {
                    IsCollapsed = false;
                    SidebarHeadingTxt.Visibility = Visibility.Visible;
                    MiddleSliderBtn.Content = new SymbolIcon(Symbol.OpenPane);

                    OpenMemberPanel();
                }
                else //Close
                {
                    IsCollapsed = true;
                    SidebarHeadingTxt.Visibility = Visibility.Collapsed;
                    MiddleSliderBtn.Content = new SymbolIcon(Symbol.ClosePane);

                    CloseMembersPanel();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void CloseMembersPanel()
        {
            try
            {
                _isOpen = false;
                //NOTE: This means without the middle button width
                double val = _model.ItemsListFlyoutWidth;

                _pdfViewCtrl.Width = (Window.Current.Bounds.Width - (PdfViewerBorder));

                var storyboard = new Storyboard();
                var moveTransform = new TranslateTransform();
                AgendaItemGrid.RenderTransform = moveTransform;
                var duration = new Duration(TimeSpan.FromSeconds(AnimeTime));
                var myDoubleAnimationX = new DoubleAnimation { Duration = duration, To = val };
                storyboard.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                storyboard.Begin();

                AdjustPdfViewer(val);
            }
            catch (Exception)
            {
            }
        }

        private double _panelWidth;
        private void OpenMemberPanel()
        {
            try
            {
                _isOpen = true;
                var tmp = Window.Current.Bounds.Width;
                var ss = tmp * PanelPropotion;
                if (tmp <= Utility.GetNarrowWidthSize())
                {
                    _model.ItemsListFlyoutWidth = Utility.GetNarrowWidthSize() - 30;
                }
                else
                {
                    if (ss < Utility.GetFlyoutDefaultWidth()) ss = Utility.GetFlyoutDefaultWidth();
                    _model.ItemsListFlyoutWidth = ss;
                }

                _panelWidth = _model.ItemsListFlyoutWidth;
                if (_panelWidth < Utility.GetFlyoutDefaultWidth())
                    _panelWidth = Utility.GetFlyoutDefaultWidth();

                double val = _panelWidth - 35;

                if (tmp > Utility.GetNarrowWidthSize())
                {
                    _pdfViewCtrl.Width = (_pdfViewCtrl.Width - (_panelWidth));
                    SetPagePresentationMode();
                }
                
                var storyboard = new Storyboard();
                var duration = new Duration(TimeSpan.FromSeconds(AnimeTime));
                var moveTransform = new TranslateTransform();
                AgendaItemGrid.RenderTransform = moveTransform;

                double sss = _panelWidth - _model.ItemsListFlyoutWidth;
                _model.ItemsListFlyoutWidth = _model.ItemsListFlyoutWidth + sss;

                //sss = (sss - 35) * -1;
                //if (sss > 0) sss = 0;
                var myDoubleAnimationX = new DoubleAnimation { Duration = duration, From = val, To = 0 };
                storyboard.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                storyboard.Begin();

                AdjustPdfViewerReverse(val);
            }
            catch (Exception)
            {
            }
        }

        private void AdjustPdfViewer(double val)
        {
            try
            {
                var grid = BoardPaperGrid;
                if (GlobalSelectdItem.DocType == (byte)DocumentType.AudioVideo)
                {
                    grid = VideoItemsGrid;
                }

                val = val * -1;
                grid.Margin = new Thickness(0, 0, val, 0);

                var moveSb = new Storyboard();
                var moveTransform = new TranslateTransform();
                grid.RenderTransform = moveTransform;
                var duration = new Duration(TimeSpan.FromSeconds(AnimeTime));
                var myDoubleAnimationX = new DoubleAnimation { Duration = duration, From = val, To = 0 };
                moveSb.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                moveSb.Begin();
            }
            catch (Exception)
            {
            }
        }

        private void AdjustPdfViewerReverse(double val)
        {
            try
            {
                var grid = BoardPaperGrid;
                if (GlobalSelectdItem.DocType == (byte)DocumentType.AudioVideo)
                {
                    grid = VideoItemsGrid;
                }

                var storyboard = new Storyboard();
                var moveTransform = new TranslateTransform();
                grid.RenderTransform = moveTransform;
                var duration = new Duration(TimeSpan.FromSeconds(AnimeTime));
                var myDoubleAnimationX = new DoubleAnimation { Duration = duration, From = val, To = 0 };
                storyboard.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                storyboard.Begin();

                grid.Margin = new Thickness(0, 0, 0, 0);
            }
            catch (Exception)
            {
            }
        }

        #endregion

        #region Paper / Media Loading

        private async Task LoadPdfDocumentToViewer(IBuffer pdfFile, InputMessageDialog dialog)
        {
            try
            {
                //GC.Collect();
                //HideVideoPlayBackView();
                //Deallocate resources used for pdf viewing
                //this.PDFViewCtrl.CloseDoc();
                //if (PDFDoc != null)
                //{
                //    PDFDoc.Destroy();
                //    PDFDoc.Dispose();
                //}

                _pdfDoc = await GetPdfDocAsync(pdfFile);

                _param = new NavigationParameter(_pdfDoc, null, null, false);
                if (_param != null)
                {
                    if (!_pdfDoc.InitStdSecurityHandler(""))
                    {
                        _oTaskCompletionSource = new TaskCompletionSource<bool>();
                        if (dialog != null) dialog.HideAsync();
                        HandlePassword();
                        var result = await _oTaskCompletionSource.Task;
                        if (!result) //PDF Password Failed
                        {
                            //NOTE: If you select the same item when the password dialog is open, without the below
                            //item will not open for the second time.
                            GlobalSelectdItem = null;
                        }
                    }
                    else
                        CommonPaperLoading();
                }
            }
            catch (Exception)
            {
                //Don't throw any exception. This is fine.
            }
        }

        private void CommonPaperLoading()
        {
            try
            {
                _pdfViewCtrl.SetDoc(_pdfDoc);

                //this.PDFFile = param.File;
                //this.Stream = param.Stream;

                /*if (param.ReadOnly)
                {
                    AppBarButton_Save.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
                else
                {
                    // This will automatically save the document every 30 seconds, provided it has been modified.
                    //_AutoSaveHelper = new Utilities.AutoSaveHelper(30);
                    //_AutoSaveHelper.PDFDoc = param.Doc;
                }*/

                if (_param.Doc.GetPageCount() > 0) //Org val 4
                {
                    ThumbnailSlider.PDFViewCtrl = _pdfViewCtrl;
                }
                else
                {
                    BottomAppBar = null;
                    _thumbSliderAppBar = null;
                }

                // register document for printing
                var docTitle = "Untitled";
                try
                {
                    docTitle = _param.Doc.GetDocInfo().GetTitle();
                }
                catch (Exception)
                {
                    // no need to do anything, it just means that the document doesn't have a title
                }
                _pdfPrintManager.RegisterForPrintingContract(_param.Doc, docTitle);

                DisplayPaperFullScreenView();
            }
            catch (Exception ex)
            {
                //var pdfNetEx = new PDFNetException(ex.HResult);
                throw;
            }
        }

        private async Task LoadPaperCommon(bool isPastPaper)
        {
            //NOTE:
            //Duplicated on AgendaPage.xaml.cs and NewsAndSharedDocsPage.xaml.cs

            #region Paper Download or Load to View

            var docTypeName = "";
            InputMessageDialog imdlg = null;
            try
            {
                DetachAppBars();
                docTypeName = BasePage.GetInstance().GetDocTypeName(GlobalSelectdItem.DocType);

                imdlg = new InputMessageDialog(docTypeName + "loading", Visibility.Collapsed, Visibility.Collapsed, true);
                imdlg.ShowAsync();

                //Check the db for download status and if its 1 and also check for the physical file.
                //if exist send the decrypted file else returns null
                IBuffer file = null;
                if (isPastPaper)
                {
                    var addSignaturePage = await _authService.GetSettingValueBySettingName(DatabaseType.UserDb, ApplicationConstants.UserDbSettingNames.AddSignaturePage);
                    if (addSignaturePage != null && !addSignaturePage.ToString().Equals("1"))  //If this setting is 1 then download the file anyway
                        file = await _agendaService.GetPastPaperPdfDocument(GlobalSelectdItem);
                }
                else
                    file = await _agendaService.GetNewsSharedDocPdfDocument(GlobalSelectdItem);
                imdlg.HideAsync();

                if (file == null) //Download the doc
                {
                    if (Global.UserForceWentOffline)
                    {
                        GlobalSelectdItem = null;
                        await _dialogService.ShowMessage("You are offline");
                        return;
                    }

                    var dlg = new DownloadingUserControl();
                    var rdm = await dlg.ShowAsync(1, null, GlobalSelectdItem);

                    if (!rdm.IsError)
                    {
                        var pdfFile = (byte[])rdm.Data;
                        //Write the encrypted file to storage, just like normal board papers. no db updates
                        if (isPastPaper)
                            await
                                _syncService.SaveEncryptedPastPaperFile(pdfFile, GlobalSelectdItem.PaperId,
                                    GlobalSelectdItem.VersionId);
                        else
                            await
                                _syncService.SaveEncryptedFile(pdfFile, GlobalSelectdItem.PaperId,
                                    GlobalSelectdItem.VersionId);

                        //Read the above file decrypt it and return
                        IBuffer decFile;
                        if (isPastPaper)
                            decFile = await _agendaService.GetPastPaperPdfDocument(GlobalSelectdItem);
                        else
                            decFile = await _agendaService.GetNewsSharedDocPdfDocument(GlobalSelectdItem);

                        if (decFile == null)
                        {
                            GlobalSelectdItem = null;
                            await _dialogService.ShowMessage(ResourceHandler.Get("err_103"));
                            return;
                        }

                        if (GlobalSelectdItem.DocType == (byte)DocumentType.AudioVideo)
                            await LoadMediaToViewer(decFile);
                        else
                            await LoadPdfDocumentToViewer(decFile, null);
                    }
                    else
                    {
                        GlobalSelectdItem = null;

                        //NOTE: -1 means its canceled by the user intentionally
                        if (!rdm.ErrorCode.Equals("-1"))
                            await _dialogService.ShowMessage(rdm.ErrorMessage);

                        return;
                    }
                }
                else //Load the pdf to the viewer
                {
                    //https://social.msdn.microsoft.com/forums/windowsapps/en-us/2c7b290a-dd84-44a7-b3f4-29abc55fe010/how-to-show-dialog-with-textbox-control
                    imdlg = new InputMessageDialog(docTypeName + "loading", Visibility.Collapsed, Visibility.Collapsed,
                        true);
                    imdlg.ShowAsync();

                    if (GlobalSelectdItem.DocType == (byte)DocumentType.AudioVideo)
                        await LoadMediaToViewer(file);
                    else
                        await LoadPdfDocumentToViewer(file, imdlg);
                }

                if (isPastPaper && _param != null)
                {
                    var agendaItem = new AgendaItem
                    {
                        Id = GlobalSelectdItem.PaperId,
                        VersionId = GlobalSelectdItem.VersionId
                    };

                    //TODO : User approval status should send from backend.
                    await BasePage.GetInstance().ImportAnnotations(_param.Doc, agendaItem);
                    _pdfViewCtrl.Update();
                }
            }
            catch (Exception)
            {
                GlobalSelectdItem = null;
                _dialogService.ShowMessage(docTypeName + "encounter an error");
            }
            finally
            {
                AttachAppBars();
                if (imdlg != null) imdlg.HideAsync();
            }

            #endregion
        }

        private async Task LoadMediaToViewer(IBuffer mediaFile)
        {
            try
            {
                MediaElementForAgenda.Stop();
                MediaElementForAgenda.Source = null;

                if (mediaFile != null)
                {
                    var stream = await Utility.ToStream(mediaFile);
                    MediaElementForAgenda.SetSource(stream, "");

                    DisplayVideoPlayBackView();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region Top AppBar

        private void DetachAppBars()
        {
            TopAppBar = null;
            BottomAppBar = null;
        }

        private void AttachAppBars()
        {
            if (TopAppBar == null)
            {
                TopAppBar = _topAppBar;
            }
            if (BottomAppBar == null)
            {
                BottomAppBar = _thumbSliderAppBar;
            }
        }

        private void CloseAppBars()
        {
            try
            {
                if (BottomAppBar != null)
                {
                    if (!_asm.GetAppBarPinnedStatus())
                        BottomAppBar.IsOpen = false;
                }
                if (TopAppBar != null)
                {
                    TopAppBar.IsOpen = false;
                }
            }
            catch (Exception)
            {
            }
        }

        private void TopAppBar_Opened(object sender, object e)
        {
            try
            {
                FindTextDialog.CloseDialog();
                OutlineDialog.CloseDialog();
                CloseThumbnailsViewer();
            }
            catch (Exception)
            {
            }
        }

        private void TopAppBar_Closed(object sender, object e)
        {
        }

        private void SearchAppBarButton_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                FindTextDialog.OpenDialog();
                CloseAppBars();
            }
            catch (Exception)
            {
            }
        }

        private void OutlineAppBarButton_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                OutlineDialog.OpenDialog();
                CloseAppBars();
                FlyoutDialogEnabled();
            }
            catch (Exception)
            {
            }
        }

        private void ViewPageAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            var vPage = sender as Button;
            var val = vPage.CommandParameter.ToString();

            switch (val)
            {
                case "fw":
                    _pdfViewCtrl.SetPageViewMode(PDFViewCtrlPageViewMode.e_fit_width);
                    _pdfViewCtrl.SetPageRefViewMode(PDFViewCtrlPageViewMode.e_fit_width);
                    break;

                case "fp":
                    _pdfViewCtrl.SetPageViewMode(PDFViewCtrlPageViewMode.e_fit_page);
                    _pdfViewCtrl.SetPageRefViewMode(PDFViewCtrlPageViewMode.e_fit_page);
                    break;
            }

            CloseAppBars();
        }

        private async void LogoutButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DetachAppBars();
                await BasePage.LogoutButton_Click(_navigationService, _dialogService, _authService);
                AttachAppBars();
            }
            catch (Exception)
            {
            }
        }

        #endregion AppBar

        #region Bottom Appbar

        private void MeetingsButton_Click(object sender, RoutedEventArgs e)
        {
            _navigationService.NavigateTo(typeof(MeetingsPage));
        }

        private void CommentButton_Click(object sender, RoutedEventArgs e)
        {
            _navigationService.NavigateTo(typeof(CommentsPage));
        }

        private void PastPapersButton_Click(object sender, RoutedEventArgs e)
        {
            _navigationService.NavigateTo(typeof(PastPapersSearchPage));
        }


        private void PinnedAppBarButton_Checked(object sender, RoutedEventArgs e)
        {
            BasePage.PinnedAppBarButton_Checked(PinnedAppBarButton, _asm);
        }

        private void PinnedAppBarButton_Unchecked(object sender, RoutedEventArgs e)
        {
            BasePage.PinnedAppBarButton_UnChecked(PinnedAppBarButton, _asm);
        }

        #endregion

        #region Goto Page

        private void GotoTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                BasePage.GetInstance().GotoTextBox_TextChanged(GotoTextBox, GotoButton, _pdfViewCtrl);
            }
            catch (Exception)
            {
            }
        }

        private void GotoTextBox_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            try
            {
                if (e.Key != VirtualKey.Enter) return;

                BasePage.GetInstance().GotoTextBox_TextChanged(GotoTextBox, GotoButton, _pdfViewCtrl);
                if (GotoButton.IsEnabled)
                    BasePage.GetInstance().GotoButton_Click(_pdfViewCtrl, GotoTextBox);
            }
            catch (Exception)
            {
            }
        }

        private void GotoButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BasePage.GetInstance().GotoButton_Click(_pdfViewCtrl, GotoTextBox);
            }
            catch (Exception)
            {
            }
        }

        #endregion
    }
}